// 数据格式
// const rules = {
//     "roles": {
//         "guest": {},
//         "reader": {
//             "permissions": ["read"],
//             "inherited": ["guest"]
//         },
//         "writer": {
//             "permissions": ["create"],
//             "inherited": ["reader"]
//         },
//         "editor": {
//             "permissions": ["update"],
//             "inherited": ["reader"],
//             "attributes": ["dailySchedule"]
//         },
//         "director": {
//             "permissions": ["delete"],
//             "inherited": ["reader", "editor"],
//         },
//         "admin": {
//             "permissions": ["manage"],
//             "inherited": ["director"],
//             "attributes": ["hasSuperPrivilege"]
//         }
//     },
//     "users": {
//         "john.smith": ["writer"],
//         "root": ["admin"]
//     }
// }

'use strict';

const Rules = module.exports = async function() {
  // 任何权限配置修改之后必须重新启动服务

  // https://www.npmjs.com/package/rbac-a
  const roles = await think.model('role').select();
  const users = await think.model('user').select();
  const rules = {roles: {}, users: {}};
  if (roles) {
    for (const role of roles) {
      let permissions = await think.model('role_auth').where({role_id: role.id}).setRelation(false).getField('id');
      // permissions=permissions.join(',').split(',');
      if (permissions.length > 0) {
        permissions = permissions.join(',').split(',');
      } else {
        permissions = [];
      }
      rules.roles[role.name] = {
        'inherited': role.parent ? [role.parent.name] : [],
        'permissions': permissions || [],
        'attributes': []
      };
    }
  }
  if (users) {
    for (const user of users) {
      let roles1 = await think.model('role')
        .alias('r')
        .join({
          table: 'user_role',
          join: 'left',
          as: 'ur',
          on: ['r.id', 'ur.role_id']
          // field:'uid'
        })
        .where({'ur.uid': user.id})
        .setRelation(false).getField('name');

      roles1 = roles1.join(',').split(',');

      rules.users[user.username] = roles1 || [];
    }
  }
  think.logger.debug(rules);

  return rules;
};
